﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Reflection;
using System.Text;

namespace sdf.Code
{
	class EntityHelper
	{
		/// <summary>
		///	Fill an sdf.EntityList<(Membership> From a DataSet
		/// </summary>
		/// <returns>populated generic list</returns>		
		public static void ValidateColumnOrdinal(IDataReader reader, Enum e, string sColumnName)
		{
			int eEnumValue = Convert.ToInt32(e);

			if ((reader.GetName(eEnumValue).ToLower() != sColumnName.ToLower()) ||
				(sColumnName.ToLower() != e.ToString().ToLower()))
			{
				throw new Exception("'" + reader.GetName(eEnumValue) + "' != '" + sColumnName + "' != '" + e.ToString() + "'");
			}
		}

		///<summary>
		/// Returns just the column name
		///</summary>
		public static string GetEnumColumnName(Enum e)
		{
			string sDbColName = "";
			string sDbColType = "";

			GetEnumDatabaseInfo(e, out sDbColName, out sDbColType);
			return sDbColName;
		}

		///<summary>
		/// Returns attributed source database object info for provided enum
		///</summary>
		public static void GetEnumDatabaseInfo(Enum e, out string sDbColName, out string sDbColType)
		{
			sDbColName = "";
			sDbColType = "";

			//attribute should not have any additional members
			Type t = e.GetType();
			MemberInfo[] members = t.GetMember(e.ToString());

			if (members != null && members.Length == 1)
			{
				object[] attrs = members[0].GetCustomAttributes(typeof(DatabaseColumnAttribute), false);
				if (attrs.Length == 1) //todo: error if not 1?
				{
					sDbColName = ((DatabaseColumnAttribute)attrs[0]).DatabaseObjectName;
					sDbColType = ((DatabaseColumnAttribute)attrs[0]).DatabaseObjectType;
				}
			}
		}
	}
}
